<!-- src/views/admin/RolePermissionManagement.vue -->
<template>
  <div class="role-permission-container">
    <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">
      <!-- 角色管理标签页 -->
      <el-tab-pane label="角色管理" name="roles">
        <div class="panel-container">
          <!-- 头部操作区 -->
          <div class="operation-bar">
            <el-button type="primary" @click="handleAddRole" :icon="Plus">新增角色</el-button>
            <div class="search-area">
              <el-input 
                v-model="roleSearch.name" 
                placeholder="角色名称" 
                clearable 
                @clear="fetchRoleList"
                style="width: 200px; margin-right: 10px;"
              />
              <el-input 
                v-model="roleSearch.code" 
                placeholder="角色编码" 
                clearable 
                @clear="fetchRoleList"
                style="width: 200px; margin-right: 10px;"
              />
              <el-select 
                v-model="roleSearch.status" 
                placeholder="状态" 
                clearable
                @clear="fetchRoleList"
                style="width: 120px; margin-right: 10px;"
              >
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
              <el-button type="primary" @click="fetchRoleList" :icon="Search">搜索</el-button>
              <el-button @click="resetRoleSearch" :icon="Refresh">重置</el-button>
            </div>
          </div>

          <!-- 角色表格 -->
          <el-table 
            :data="roleList" 
            border 
            style="width: 100%" 
            v-loading="roleLoading" 
            row-key="id"
          >
            <el-table-column prop="id" label="角色ID" width="80" />
            <el-table-column prop="name" label="角色名称" width="150" />
            <el-table-column prop="code" label="角色编码" width="150" />
            <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
            <el-table-column label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                  {{ row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.createdTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="350" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEditRole(row)">
                  <el-icon><Edit /></el-icon> 编辑
                </el-button>
                <el-button type="success" link @click="handleAssignPermissions(row)">
                  <el-icon><Key /></el-icon> 权限设置
                </el-button>
                <el-button 
                  type="info" 
                  link
                  @click="handleToggleRoleStatus(row)"
                  :disabled="row.code === 'ADMIN' && row.status === 1"
                >
                  <el-icon>
                    <component :is="row.status === 1 ? 'Lock' : 'Unlock'" />
                  </el-icon>
                  {{ row.status === 1 ? '禁用' : '启用' }}
                </el-button>
                <el-button 
                  type="danger" 
                  link
                  @click="handleDeleteRole(row)"
                  :disabled="row.code === 'ADMIN'"
                >
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="rolePagination.current"
              v-model:page-size="rolePagination.size"
              :page-sizes="[10, 20, 50, 100]"
              :total="rolePagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleRoleSizeChange"
              @current-change="handleRoleCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>

      <!-- 权限管理标签页 -->
      <el-tab-pane label="权限管理" name="permissions">
        <div class="panel-container">
          <!-- 头部操作区 -->
          <div class="operation-bar">
            <el-button type="primary" @click="handleAddPermission" :icon="Plus">新增权限</el-button>
            <div class="search-area">
              <el-input 
                v-model="permSearch.name" 
                placeholder="权限名称" 
                clearable 
                @clear="filterPermissionTable"
                @input="filterPermissionTable"
                style="width: 200px; margin-right: 10px;"
              />
              <el-input 
                v-model="permSearch.code" 
                placeholder="权限编码" 
                clearable 
                @clear="filterPermissionTable"
                @input="filterPermissionTable"
                style="width: 200px; margin-right: 10px;"
              />
                <el-select 
    v-model="permSearch.status" 
    placeholder="状态" 
    clearable
    @clear="filterPermissionTable"
    @change="filterPermissionTable"
    style="width: 120px; margin-right: 10px;"
  >
    <el-option label="全部" :value="null" />
    <el-option label="启用" :value="1" />
    <el-option label="禁用" :value="0" />
  </el-select>
              <el-button type="primary" @click="filterPermissionTable" :icon="Search">搜索</el-button>
              <el-button @click="resetPermSearch" :icon="Refresh">重置</el-button>
            </div>
          </div>

          <!-- 权限表格 -->
          <el-table 
            :data="filteredPermissions" 
            border 
            style="width: 100%" 
            v-loading="permLoading" 
            row-key="id"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            default-expand-all
          >
            <el-table-column prop="id" label="权限ID" width="80" />
            <el-table-column prop="name" label="权限名称" width="150" />
            <el-table-column prop="code" label="权限编码" width="150" />
            <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                  {{ row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.createdTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEditPermission(row)">
                  <el-icon><Edit /></el-icon> 编辑
                </el-button>
                <el-button 
                  type="info" 
                  link
                  @click="handleTogglePermissionStatus(row)"
                >
                  <el-icon>
                    <component :is="row.status === 1 ? 'Lock' : 'Unlock'" />
                  </el-icon>
                  {{ row.status === 1 ? '禁用' : '启用' }}
                </el-button>
                <el-button 
                  type="danger" 
                  link
                  @click="handleDeletePermission(row)"
                  :disabled="hasChildren(row) || row.code === 'ADMIN_PERMISSION'"
                >
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="isEditRole ? '编辑角色' : '新增角色'"
      width="500px"
      @close="resetRoleForm"
      destroy-on-close
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
        class="role-form"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input 
            v-model="roleForm.code" 
            placeholder="请输入角色编码" 
            :disabled="isEditRole && roleForm.code === 'ADMIN'"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="roleForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitRoleForm">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限表单对话框 -->
    <el-dialog
      v-model="permDialogVisible"
      :title="isEditPerm ? '编辑权限' : '新增权限'"
      width="600px"
      @close="resetPermForm"
      destroy-on-close
    >
      <el-form
        ref="permFormRef"
        :model="permForm"
        :rules="permRules"
        label-width="100px"
        class="perm-form"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input 
            v-model="permForm.code" 
            placeholder="请输入权限编码" 
            :disabled="isEditPerm && permForm.code === 'ADMIN_PERMISSION'"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="permForm.sortOrder" :min="0" :max="999" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="permForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="permForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="permDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitPermForm">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      v-model="permAssignDialogVisible"
      title="角色权限设置"
      width="600px"
      @close="resetPermAssignForm"
    >
      <div v-if="currentRole" class="perm-assign-content">
        <div class="role-info">
          <h3>{{ currentRole.name }}</h3>
          <p class="role-description">{{ currentRole.description || '无描述' }}</p>
        </div>
        
        <div class="perm-search">
          <el-input
            v-model="permSearchKey"
            placeholder="搜索权限"
            :prefix-icon="Search"
            clearable
            @input="filterPermTree"
          />
        </div>
        
        <el-tree
          ref="permTreeRef"
          :data="filteredPermTree"
          show-checkbox
          node-key="id"
          :props="{ label: 'name', children: 'children' }"
          :default-expand-all="permTree.length < 30"
          :filter-node-method="filterNode"
          class="perm-tree"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <div class="node-content">
                <el-icon v-if="data.icon" :size="16" class="node-icon">
                  <component :is="data.icon" />
                </el-icon>
                <el-tag v-if="data.type" size="small" :type="getPermissionTypeTag(data.type)" class="node-type">
                  {{ getPermissionTypeText(data.type) }}
                </el-tag>
                <el-tooltip :content="data.description" placement="top" :disabled="!data.description">
                  <span class="node-label">{{ node.label }}</span>
                </el-tooltip>
              </div>
              <span class="perm-code" v-if="data.code">{{ data.code }}</span>
            </div>
          </template>
        </el-tree>
        
        <div class="tree-actions">
          <el-button size="small" @click="handleCheckAll">全选</el-button>
          <el-button size="small" @click="handleUncheckAll">取消全选</el-button>
          <el-button 
            size="small" 
            type="primary" 
            @click="handleToggleExpand"
          >{{ treeExpanded ? '折叠全部' : '展开全部' }}</el-button>
        </div>
      </div>
      <template #footer>
        <el-button @click="permAssignDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitPermAssign">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue';
import { 
  Search, Plus, Edit, Delete, Key, Refresh, 
  Lock, Unlock, Menu, Operation, Connection 
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getRoleList, addRole, updateRole, deleteRole, updateRoleStatus,
  assignPermissions, getRolePermissions
} from '@/api/role';
import {
  getPermissionTree, getAllPermissions, addPermission, 
  updatePermission, deletePermission, updatePermissionStatus
} from '@/api/permission';

// ==== 共享状态 ====
const activeTab = ref('roles');
const submitLoading = ref(false);

// ==== 角色管理 ====
const roleList = ref([]);
const roleLoading = ref(false);
const rolePagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

const roleSearch = reactive({
  name: '',
  code: '',
  status: null
});

// 角色表单相关
const roleDialogVisible = ref(false);
const isEditRole = ref(false);
const roleFormRef = ref(null);
const roleForm = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  status: 1
});

// 角色表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ]
};

// ==== 权限管理 ====
const permissionList = ref([]);
const filteredPermissions = ref([]);
const permLoading = ref(false);

const permSearch = reactive({
  name: '',
  code: '',
  status: null
});

// 权限表单相关
const permDialogVisible = ref(false);
const isEditPerm = ref(false);
const permFormRef = ref(null);
const permissionOptions = ref([]);
// 权限表单数据
const permForm = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  sortOrder: 0,
  status: 1
});

// 权限表单验证规则
const permRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
};

// ==== 权限分配 ====
const permAssignDialogVisible = ref(false);
const currentRole = ref(null);
const permTree = ref([]);
const filteredPermTree = ref([]);
const permTreeRef = ref(null);
const permSearchKey = ref('');
const treeExpanded = ref(false);

// ============= 初始化 =============
onMounted(() => {
  fetchRoleList();
  if (activeTab.value === 'permissions') {
    fetchPermissionList();
  }
});
const getPermissionTypeTag = (type) => {
  switch (type) {
    case 1: return 'info';     // 菜单
    case 2: return 'warning';  // 按钮
    case 3: return 'success';  // 链接
    default: return '';
  }
};

// 【新增】权限类型对应的文字
const getPermissionTypeText = (type) => {
  switch (type) {
    case 1: return '菜单';
    case 2: return '按钮';
    case 3: return '链接';
    default: return '';
  }
};

// 【新增】展开所有节点
const expandAllNodes = () => {
  const tree = permTreeRef.value;
  if (!tree?.store) return;
  tree.store.root.childNodes.forEach(node => node.expand());
};

// 【新增】折叠所有节点
const collapseAllNodes = () => {
  const tree = permTreeRef.value;
  if (!tree?.store) return;
  tree.store.root.childNodes.forEach(node => node.collapse());
};

// 监听标签页切换
const handleTabClick = (tab) => {
  if (tab.props.name === 'permissions' && permissionList.value.length === 0) {
    fetchPermissionList();
  } else if (tab.props.name === 'roles' && roleList.value.length === 0) {
    fetchRoleList();
  }
};

// 监听权限搜索关键字
watch(permSearchKey, () => {
  filterPermTree();
});

// ============= 角色相关方法 =============

// 获取角色列表
const fetchRoleList = async () => {
  try {
    roleLoading.value = true;
    const params = {
      pageNum: rolePagination.current,
      pageSize: rolePagination.size,
      name: roleSearch.name || undefined,
      code: roleSearch.code || undefined,
      status: roleSearch.status || undefined
    };
    
    const res = await getRoleList(params);
    console.info("角色",res)
    if (res.data.code === 200) {
      roleList.value = res.data.data.records || [];
      rolePagination.total = res.data.data.total || 0;
    } else {
      ElMessage.error(res.message || '获取角色列表失败');
    }
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error('获取角色列表失败');
  } finally {
    roleLoading.value = false;
  }
};

// 处理角色分页大小变化
const handleRoleSizeChange = (size) => {
  rolePagination.size = size;
  rolePagination.current = 1;
  fetchRoleList();
};

// 处理角色分页页码变化
const handleRoleCurrentChange = (current) => {
  rolePagination.current = current;
  fetchRoleList();
};

// 重置角色搜索条件
const resetRoleSearch = () => {
  roleSearch.name = '';
  roleSearch.code = '';
  roleSearch.status = null;
  fetchRoleList();
};

// 处理添加角色
const handleAddRole = () => {
  isEditRole.value = false;
  roleForm.id = null;
  roleForm.name = '';
  roleForm.code = '';
  roleForm.description = '';
  roleForm.status = 1;
  roleDialogVisible.value = true;
};

// 处理编辑角色
const handleEditRole = (row) => {
  isEditRole.value = true;
  roleForm.id = row.id;
  roleForm.name = row.name;
  roleForm.code = row.code;
  roleForm.description = row.description || '';
  roleForm.status = row.status;
  roleDialogVisible.value = true;
};

// 提交角色表单
const submitRoleForm = async () => {
  if (!roleFormRef.value) return;
  
  try {
    await roleFormRef.value.validate();
    submitLoading.value = true;
    
    let res;
    if (isEditRole.value) {
      res = await updateRole(roleForm.id, roleForm);
    } else {
      res = await addRole(roleForm);
    }
    
    if (res.data.code === 200) {
      ElMessage.success(isEditRole.value ? '角色更新成功' : '角色添加成功');
      roleDialogVisible.value = false;
      fetchRoleList();
    } else {
      ElMessage.error(res.message || (isEditRole.value ? '角色更新失败' : '角色添加失败'));
    }
  } catch (error) {
    console.error('提交角色表单失败:', error);
    ElMessage.error(isEditRole.value ? '角色更新失败' : '角色添加失败');
  } finally {
    submitLoading.value = false;
  }
};

// 重置角色表单
const resetRoleForm = () => {
  if (roleFormRef.value) {
    roleFormRef.value.resetFields();
  }
};

// 处理删除角色
const handleDeleteRole = (row) => {
  if (row.code === 'ADMIN') {
    ElMessage.warning('不能删除系统管理员角色');
    return;
  }
  
  ElMessageBox.confirm(`确认删除角色"${row.name}"吗？此操作不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteRole(row.id);
      if (res.data.code === 200) {
        ElMessage.success('角色删除成功');
        fetchRoleList();
      } else {
        ElMessage.error(res.message || '角色删除失败');
      }
    } catch (error) {
      console.error('删除角色失败:', error);
      ElMessage.error('角色删除失败');
    }
  }).catch(() => {});
};

// 处理角色状态切换
const handleToggleRoleStatus = (row) => {
  if (row.code === 'ADMIN' && row.status === 1) {
    ElMessage.warning('不能禁用系统管理员角色');
    return;
  }
  
  const newStatus = row.status === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? '启用' : '禁用';
  
  ElMessageBox.confirm(`确认${statusText}角色"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await updateRoleStatus(row.id, newStatus);
      if (res.data.code === 200) {
        ElMessage.success(`角色${statusText}成功`);
        fetchRoleList();
      } else {
        ElMessage.error(res.message || `角色${statusText}失败`);
      }
    } catch (error) {
      console.error(`角色${statusText}失败:`, error);
      ElMessage.error(`角色${statusText}失败`);
    }
  }).catch(() => {});
};

// ============= 权限相关方法 =============

// 获取权限列表
const fetchPermissionList = async () => {
  try {
    permLoading.value = true;
    const res = await getAllPermissions();
    console.log("权限列表:", res);
    if (res.data.code === 200) {
      permissionList.value = res.data.data || [];
      filteredPermissions.value = permissionList.value;
      
      // 转换为级联选择器选项
      permissionOptions.value = JSON.parse(JSON.stringify(permissionList.value));
    } else {
      ElMessage.error(res.message || '获取权限列表失败');
    }
  } catch (error) {
    console.error('获取权限列表失败:', error);
    ElMessage.error('获取权限列表失败');
  } finally {
    permLoading.value = false;
  }
};

// 过滤权限表格
const filterPermissionTable = () => {
  const { name, code, status } = permSearch;
  
  if (!name && !code && status === null) {
    filteredPermissions.value = permissionList.value;
    return;
  }

  const filterNodes = (nodes) => {
    return nodes.filter(node => {
      const nameMatch = !name || node.name.toLowerCase().includes(name.toLowerCase());
      const codeMatch = !code || (node.code && node.code.toLowerCase().includes(code.toLowerCase()));
      const statusMatch = status === null || node.status === status;

      if (nameMatch && codeMatch && statusMatch) {
        return true;
      }

      if (node.children?.length) {
        const filteredChildren = filterNodes(node.children);
        if (filteredChildren.length) {
          node.children = filteredChildren;
          return true;
        }
      }
      return false;
    });
  };

  const tempPermissions = JSON.parse(JSON.stringify(permissionList.value));
  filteredPermissions.value = filterNodes(tempPermissions);
};

// 重置权限搜索条件
const resetPermSearch = () => {
  permSearch.name = '';
  permSearch.code = '';
  permSearch.status = null;
  filteredPermissions.value = permissionList.value;
};

// 处理添加权限
const handleAddPermission = () => {
  isEditPerm.value = false;
  permForm.id = null;
  permForm.name = '';
  permForm.code = '';
  permForm.description = '';
  permForm.type = 1;
  permForm.parentId = null;
  permForm.path = '';
  permForm.component = '';
  permForm.icon = '';
  permForm.sortOrder = 0;
  permForm.status = 1;
  permDialogVisible.value = true;
};

// 处理编辑权限
const handleEditPermission = (row) => {
  isEditPerm.value = true;
  permForm.id = row.id;
  permForm.name = row.name;
  permForm.code = row.code;
  permForm.description = row.description || '';
  permForm.type = row.type;
  permForm.parentId = row.parentId;
  permForm.path = row.path || '';
  permForm.component = row.component || '';
  permForm.icon = row.icon || '';
  permForm.sortOrder = row.sortOrder || 0;
  permForm.status = row.status;
  permDialogVisible.value = true;
};

// 提交权限表单
const submitPermForm = async () => {
  if (!permFormRef.value) return;
  
  try {
    await permFormRef.value.validate();
    submitLoading.value = true;
    
    let res;
    if (isEditPerm.value) {
      res = await updatePermission(permForm.id, permForm);
    } else {
      res = await addPermission(permForm);
    }
    console.info("提交权限表单",res);
    if (res.data.code === 200) {
      ElMessage.success(isEditPerm.value ? '权限更新成功' : '权限添加成功');
      permDialogVisible.value = false;
      fetchPermissionList();
    } else {
      ElMessage.error(res.message || (isEditPerm.value ? '权限更新失败' : '权限添加失败'));
    }
  } catch (error) {
    console.error('提交权限表单失败:', error);
    ElMessage.error(isEditPerm.value ? '权限更新失败' : '权限添加失败');
  } finally {
    submitLoading.value = false;
  }
};

// 重置权限表单
const resetPermForm = () => {
  if (permFormRef.value) {
    permFormRef.value.resetFields();
  }
};

// 处理删除权限
const handleDeletePermission = (row) => {
  if (row.code === 'ADMIN_PERMISSION') {
    ElMessage.warning('不能删除系统核心权限');
    return;
  }
  
  if (hasChildren(row)) {
    ElMessage.warning('该权限包含子权限，不能直接删除');
    return;
  }
  
  ElMessageBox.confirm(`确认删除权限"${row.name}"吗？此操作不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deletePermission(row.id);
      if (res.data.code === 200) {
        ElMessage.success('权限删除成功');
        fetchPermissionList();
      } else {
        ElMessage.error(res.message || '权限删除失败');
      }
    } catch (error) {
      console.error('删除权限失败:', error);
      ElMessage.error('权限删除失败');
    }
  }).catch(() => {});
};

// 处理权限状态切换
const handleTogglePermissionStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? '启用' : '禁用';
  
  ElMessageBox.confirm(`确认${statusText}权限"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await updatePermissionStatus(row.id, newStatus);
      if (res.data.code === 200) {
        ElMessage.success(`权限${statusText}成功`);
        fetchPermissionList();
      } else {
        ElMessage.error(res.message || `权限${statusText}失败`);
      }
    } catch (error) {
      console.error(`权限${statusText}失败:`, error);
      ElMessage.error(`权限${statusText}失败`);
    }
  }).catch(() => {});
};

// 检查是否有子权限
const hasChildren = (row) => {
  return row.children && row.children.length > 0;
};


// 处理分配权限
const handleAssignPermissions = async (row) => {
  currentRole.value = row;
  permAssignDialogVisible.value = true;
  permSearchKey.value = '';
  treeExpanded.value = false;
  
  try {
    // 获取权限树
    const treeRes = await getPermissionTree();
    if (treeRes.data.code === 200) {
      permTree.value = treeRes.data.data || [];
      filteredPermTree.value = permTree.value;
      
      // 获取角色已有权限
      const rolePermsRes = await getRolePermissions(row.id);
      if (rolePermsRes.data.code === 200 && permTreeRef.value) {
        const permIds = rolePermsRes.data.data.map(p => p.id);
        nextTick(() => {
          permTreeRef.value.setCheckedKeys(permIds);
        });
      }
    } else {
      ElMessage.error(treeRes.message || '获取权限树失败');
    }
  } catch (error) {
    console.error('获取权限数据失败:', error);
    ElMessage.error('获取权限数据失败');
  }
};

// 过滤权限树
const filterPermTree = () => {
  if (!permSearchKey.value) {
    filteredPermTree.value = permTree.value;
    return;
  }
  
  if (permTreeRef.value) {
    permTreeRef.value.filter(permSearchKey.value);
  }
};

// 树节点过滤方法
const filterNode = (value, data) => {
  if (!value) return true;
  
  // 检查当前节点
  const matchesName = data.name.toLowerCase().includes(value.toLowerCase());
  const matchesCode = data.code && data.code.toLowerCase().includes(value.toLowerCase());
  const matchesDescription = data.description && data.description.toLowerCase().includes(value.toLowerCase());
  
  // 如果当前节点匹配，返回true
  if (matchesName || matchesCode || matchesDescription) {
    return true;
  }
  
  // 如果当前节点有子节点，递归检查
  if (data.children && data.children.length) {
    return data.children.some(child => filterNode(value, child));
  }
  
  return false;
};

// 全选权限
const handleCheckAll = () => {
  if (permTreeRef.value) {
    const allKeys = getAllKeys(permTree.value);
    permTreeRef.value.setCheckedKeys(allKeys);
  }
};

// 取消全选权限
const handleUncheckAll = () => {
  if (permTreeRef.value) {
    permTreeRef.value.setCheckedKeys([]);
  }
};

// 获取所有权限ID
const getAllKeys = (nodes) => {
  let keys = [];
  
  const getKeys = (nodes) => {
    nodes.forEach(node => {
      keys.push(node.id);
      if (node.children && node.children.length) {
        getKeys(node.children);
      }
    });
  };
  
  getKeys(nodes);
  return keys;
};

// 展开/折叠树
const handleToggleExpand = () => {
  if (treeExpanded.value) {
    collapseAllNodes();
  } else {
    expandAllNodes();
  }
  treeExpanded.value = !treeExpanded.value;
};

// 提交权限分配
const submitPermAssign = async () => {
  if (!currentRole.value || !permTreeRef.value) return;
  
  try {
    submitLoading.value = true;
    
    // 获取选中的权限ID
    const checkedKeys = permTreeRef.value.getCheckedKeys();
    const halfCheckedKeys = permTreeRef.value.getHalfCheckedKeys();
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys];
    
    const res = await assignPermissions(currentRole.value.id, allCheckedKeys);
    
    if (res.data.code === 200) {
      ElMessage.success('权限分配成功');
      permAssignDialogVisible.value = false;
    } else {
      ElMessage.error(res.message || '权限分配失败');
    }
  } catch (error) {
    console.error('分配权限失败:', error);
    ElMessage.error('权限分配失败');
  } finally {
    submitLoading.value = false;
  }
};

// 重置权限分配表单
const resetPermAssignForm = () => {
  currentRole.value = null;
  permSearchKey.value = '';
  if (permTreeRef.value) {
    permTreeRef.value.setCheckedKeys([]);
  }
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '--';
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};


</script>

<style scoped>
.role-permission-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  min-height: calc(100vh - 120px);
}

.panel-container {
  margin-top: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 权限分配对话框样式 */
.perm-assign-content {
  min-height: 400px;
  max-height: 60vh;
  display: flex;
  flex-direction: column;
}

.role-info {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.role-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
}.role-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.perm-search {
  margin-bottom: 16px;
}

.perm-tree {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}

.tree-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: 10px;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding-right: 8px;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 6px;
}

.node-icon {
  color: #606266;
}

.node-type {
  font-size: 11px;
  padding: 0 5px;
}

.node-label {
  font-size: 14px;
}

.perm-code {
  color: #909399;
  font-size: 12px;
  background-color: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column;
    gap: 10px;
  }
  
  .search-area {
    margin-top: 10px;
  }
  
  .tree-actions {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>